package com.powernode.lambda.simpleStream;


import java.util.*;
import java.util.function.*;

/**
 * 自己实现简单的collect方法
 */
public class SimpleStream02<T> {

    private Collection<T> collection;
    private SimpleStream02(Collection<T> collection) {
        this.collection =collection;
    }

    /**
     * 根据给出的链式调用手写出需要调用的方法
     * @param args
     */
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(1);
        list.add(2);


        System.out.println("StringBuilder = " + SimpleStream02.of(list).collect(() -> new StringBuilder(), (x, y) -> {
            x.append(y);
        }));
        System.out.println("HashSet = " + SimpleStream02.of(list).collect(() -> new HashSet(), (x, y) -> {
            x.add(y);
        }));
        System.out.println("StringJoiner = " + SimpleStream02.of(list).collect(() -> new StringJoiner("-"), (x, y) -> x.add(y.toString())));
    }

    /**
     * 收集元素思路：
     * 不知道容器类型(List?StringBuilder?Map?):
     *      new ArrayList 返回，无参有返回值，对应supplier
     * 不知道以哪种方式添加(add?append?put?)
     *      传入添加规则和数据，两个参数无返回值，对应BiConsumer
     */
    public <C> C collect(Supplier<C> supplier,BiConsumer<C,T> biConsumer){
        C c = supplier.get();   //创建容器
        for (T t : collection) {
            biConsumer.accept(c,t);//添加元素
        }
        return c;
    }


    public static <T> SimpleStream02<T> of(Collection<T> collection){
        return new SimpleStream02<>(collection);
    }


}
